import axios from "axios";
import * as vscode from 'vscode';
import { ajaxDenpencies } from "./models/ajaxDenpencies";
import { denpenciesContent } from "./models/denpenciesContent";

export class client {
    private static _keywords: string;
    private static _page_count: number;
    private static _denpencies: denpenciesContent[];
    static get page_count() {
        return this._page_count;
    }
    static get denpencies() {
        return this._denpencies;
    }

    static async query(keywords?: string) {
        try {
            this._keywords = keywords ?? '';
            let url = `https://web-api.gitcode.com/api/v2/groups/Cangjie-TPC/projects?orgId=Cangjie-TPC&page=1&per_page=10&simple=false&include_subgroups=true&search=${this._keywords}&order_by=&sort=`;
            let response = await axios({
                url: url,
                method: 'get',
                headers: {
                    'Origin': 'https://gitcode.com',
                    'Referer': 'https://gitcode.com'
                }
            });
            if (response.status === 200) {
                let data: ajaxDenpencies = response.data;
                this._page_count = data.page_count;
                this._denpencies = data.content;
                return data.content;
            } else {
                vscode.window.showErrorMessage(`Load Denpencies Failed, ${response.data}`);
            }
        } catch (err) {
            vscode.window.showErrorMessage(`Load Denpencies Failed, ${err}`);
        }
    }
    static async load(page_num: number) {
        try {
            if (this._page_count >= page_num) {
                let url = `https://web-api.gitcode.com/api/v2/groups/Cangjie-TPC/projects?orgId=Cangjie-TPC&page=${page_num}&per_page=10&simple=false&include_subgroups=true&search=${this._keywords}&order_by=&sort=`;
                let response = await axios({
                    url: url,
                    method: 'get',
                    headers: {
                        'Origin': 'https://gitcode.com',
                        'Referer': 'https://gitcode.com'
                    }
                });
                if (response.status === 200) {
                    let data: ajaxDenpencies = response.data;
                    this._denpencies.push(...data.content);
                    return data.content;
                } else {
                    vscode.window.showErrorMessage(`Load Denpencies Failed, ${response.data}`);
                }
            }
        } catch (err) {
            vscode.window.showErrorMessage(`Load Denpencies Failed, ${err}`);
        }
    }
}